#include "select.h"
#include "cam.h"
#include "drive.h"
#include "Com_format.h"
#include "Com_tcp.h"
int my_select(int sockfd)
{
     // IO并发发送环境数据和视频
    int fd_cam = 0;
    //采用select实现io并发
    // Select

    // 连接摄像头 返回摄像头文件描述符
    fd_cam = cam_init();
    struct v4l2_buffer vbuf;
    // 连接小车
    //创建文件描述符集合
    fd_set rfd1, rfd2;
    //清空集合
    FD_ZERO(&rfd1);
    //将待操作的文件描述符加入到集合
    FD_SET(fd_cam, &rfd1); //摄像头                    

    //设置最大文件描述符
    int maxfd = sockfd;
    if (maxfd < fd_cam)
    {
        maxfd = fd_cam;
    }
    maxfd++;
    // int maxfd = 1;
    // int maxfd = sockfd + 1;
#if 0
    //设置超时时间 -- 可选
    struct timeval tv1,tv2;
    tv1.tv_sec = 2;//秒数
    tv1.tv_usec = 0;//微秒
    tv2.tv_sec = 2;//秒数
    tv2.tv_usec = 0;//微秒
#endif

    while (1)
    {
        rfd2 = rfd1; //重置文件描述符
        int ret = select(maxfd, &rfd2, NULL, NULL, NULL);
        if (-1 == ret)
        {
            camera_exit(fd_cam);
            perror("select");
            continue;
        }
        if (ret == 0)
        {
            printf("time out\n");
            continue;
        }
        //打印调试
        // printf("ret = %d\n",ret);
        //判断集合中置位的文件描述是谁
        if (FD_ISSET(fd_cam, &rfd2))
        {
            //摄像头文件描述符处理

            vbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
            vbuf.memory = V4L2_MEMORY_MMAP;
            int rv = ioctl(fd_cam, VIDIOC_DQBUF, &vbuf); //出队,也就是从用户空间取出图片
            if (rv == -1)
            {
                perror("camera->dqbuf");
                return -1;
            }
            // 获取视频数据
            char *buf = bufs[vbuf.index].start;
            // 视频数据大小
            unsigned int size = vbuf.bytesused;
            //图片index
            int index = vbuf.index;

            // 发送图片
            struct cam_t img_data;
            img_data.pic_len = size;
            memcpy(img_data.pic_buf, buf, size);
            char *com = (char *)malloc(size + 13);
            //printf("size data %d\n", size);

            char *p = com;
            int top = COM_TOP;
            memcpy((void *)com, (void *)&top, 4);
            com += 4;

            long long data_size = size;
            memcpy((void *)com, (void *)&data_size, 8);
            com += 8;

            enum COM_CMD_TYPE one = VIDEO;
            char c = one;
            memcpy((void *)com, (void *)&c, 1);
            com += 1;

            memcpy((void *)com, (void *)buf, size);
            com = p;
            // packCmdData_cam_t(img_data, &com);

            datasend(sockfd, com);
            free(com);
            camera_eqbuf(fd_cam, index);
        }
    }
    camera_stop(fd_cam);
    camera_exit(fd_cam);
    return 0;
}